package XML;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
public class WriteXML {
	
		
	/**
	 * This class construcs an XML document in memory using DOM.
	 * It first creates the root Order element and subsequently creates components
	 * of the order by inserting nodes to the root element.
	 */
	private static Document CreateOrderDOM(String root, Document doc)
    {
        DocumentBuilder builder = null;
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        try
        {
            builder = factory.newDocumentBuilder();
          doc = builder.newDocument();

        }
        catch (ParserConfigurationException e)
        {
            e.printStackTrace();
        }                
        Element _root = (Element) doc.createElement(root);        
        doc.appendChild(_root);
        // Normalizing the DOM
        doc.getDocumentElement().normalize();
        return doc;
  }
	
	   
	
	  private static Document insertRoot(Document doc, String fName, String root)
	  {
		  // Build new DOM Document
	         doc = CreateOrderDOM(root, doc);
	         //kiem tra fileName da ton tai hay chua
	         File f = new File(fName);
	         if(!f.exists())
	         {
	             // Print XML content
	             //DOMUltil.printDOM(doc);

	             // Write to a file
	             DOMUltil.writeXmlToFile(fName,doc);	             
	         }  
	         return doc;
	  }
	  
	  private static Document insertTag(Document doc, String fName, Node parent, String tagName, String val)
	  {
		  //insert tag
		  Node itemChild = doc.createElement(tagName);
		  parent.appendChild(itemChild);
		  
		  Node value = doc.createTextNode(val);
		  itemChild.appendChild(value);
		  
		  DOMUltil.writeXmlToFile(fName, doc);
		  return doc;
	  }
	  
	  private static Document insertItemIP(Document doc, Node parent, int id, String userName, String fullName, int idclass, String ip)
	  {
		// Insert child Item
			Element e = doc.createElement("Learner");
			parent.appendChild(e);

			e.setAttribute("UserName", userName);
			e.setAttribute("ID", ""+id);
			e.setAttribute("FullName", fullName);
			e.setAttribute("IDClass", idclass+"");
			
			//tạo node ip
			Node nodeChild = doc.createElement("IP");
			e.appendChild(nodeChild);

			Node vaule = doc.createTextNode(ip);
			nodeChild.appendChild(vaule);
			return doc;
	  }
	  
	
	/**
	 * Hàm xoá một IP trong listIP
	 * @param doc
	 * @param fName
	 * @param ip
	 * @return
	 */
	public static Document deleteIP(Document doc, String fName, String ip)
	{
		
		if(doc != null)
		{
			DOMUltil.printDOM(doc);
			NodeList ipList = doc.getElementsByTagName("Learner");
			int n = ipList.getLength();
			for(int i = 0; i< n; i++)
			{
				Node noteip = ipList.item(i);
				Node nip = noteip.getChildNodes().item(0);
				if(nip.getTextContent().equals(ip))
				{
					noteip.getParentNode().removeChild(noteip);
					break;
				}
			}
			
		}
		DOMUltil.writeXmlToFile(fName,doc);
		return doc;
	}
	
	public static Document deleteIP(Document doc, String fName, int id)
	{
		if(doc != null)
		{
			NodeList resList = doc.getElementsByTagName("Learner");
			int n = resList.getLength();
			for(int i = 0; i< n; i++)
			{
				Element e = (Element)resList.item(i);
				if(e.getAttribute("ID").equals(""+id))
				{
					Node parent = e.getParentNode();
				  	parent.removeChild(e);
				}
				break;
			}					
		}
		DOMUltil.writeXmlToFile(fName,doc);
		return doc;
	}
	
	//Xóa một Learner trong listip
	public static Document deleteIPFromUsername(Document doc, String fName, String sUsername)
	{
		if(doc != null)
		{
			NodeList resList = doc.getElementsByTagName("Learner");
			int n = resList.getLength();
			for(int i = 0; i< n; i++)
			{
				Element e = (Element)resList.item(i);
				if(e.getAttribute("UserName").equals(sUsername))
				{
					Node parent = e.getParentNode();
				  	parent.removeChild(e);
				  	break;
				}
			}					
		}
		DOMUltil.writeXmlToFile(fName,doc);
		return doc;
	}
	
	/**
	 * hàm insert một ip vào ip List
	 * @param doc
	 * @param fName
	 * @param ip
	 * @return
	 */
	public static Document insertIP(Document doc, String fName, int id, String userName, String fullName, int idclass, String ip)
	{
		if(doc != null)
        {
            Node item = doc.getElementsByTagName("IPList").item(0);
            DOMUltil.printDOM(item);
            doc = insertItemIP(doc, item, id, userName, fullName, idclass, ip);
        }
        
        DOMUltil.writeXmlToFile(fName,doc);
        return doc;
	}
	
	/**
	 * Hàm tạo cấu trúc file IPlist, lưu ý cần gọi hàm này trước khi gọi hàm insert ip
	 * @param doc
	 * @param fName
	 * @return
	 */
	public static Document WriteXMLIP(Document doc, String fName)
	{
		return insertRoot(doc, fName, "IPList");
	}
	
	//Thông tin cấu hình
	 private static Document insertItemCH(Document doc, Node parent, 
			 String Servername, String userName, String password, String ip, 
			 String UserNameLearner, String PassLearner, boolean autologin)
	  {
		// Insert child Item
			Element e = doc.createElement("Info");
			parent.appendChild(e);

			e.setAttribute("ServerName", Servername);
			e.setAttribute("AccServer", userName);
			e.setAttribute("PassServer", password);
			e.setAttribute("IP", ip);
			e.setAttribute("AccLearner", UserNameLearner);
			e.setAttribute("PassLearner", PassLearner);
			e.setAttribute("AutoLogin", autologin+"");
			
			
			return doc;
	  }
	 //////////////////////////////////////////////////////////////////////////////////////////
	 
	 /**
	  * Delete cấu hình
	  */
		public static Document deleteCH(Document doc, String fName, String Servername)
		{
			if(doc != null)
			{
				NodeList resList = doc.getElementsByTagName("Info");
				int n = resList.getLength();
				for(int i = 0; i< n; i++)
				{
					Element e = (Element)resList.item(i);
					if(e.getAttribute("ServerName").equals(Servername))
					{
						Node parent = e.getParentNode();
					  	parent.removeChild(e);
					}
					break;
				}					
			}
			DOMUltil.writeXmlToFile(fName,doc);
			return doc;
		}
		/**
		  * Delete cấu hình theo username
		  */
		//Xóa một Learner trong listip
		public static Document deleteCHFromUsername(Document doc, String fName, String sUsername)
		{
			if(doc != null)
			{
				NodeList resList = doc.getElementsByTagName("Info");
				int n = resList.getLength();
				for(int i = 0; i< n; i++)
				{
					Element e = (Element)resList.item(i);
					if(e.getAttribute("AccLearner").equals(sUsername))
					{
						Node parent = e.getParentNode();
					  	parent.removeChild(e);
					}
					break;
				}					
			}
			DOMUltil.writeXmlToFile(fName,doc);
			return doc;
		}
		/**
		 * hàm insert một ip vào ip List
		 * @param doc
		 * @param fName
		 * @param ip
		 * @return
		 */
		public static Document insertCH(Document doc, String fName, 
				 String Servername, String userName, String password, String ip, 
				 String UserNameLearner, String PassLearner, boolean autologin)
		{
			if(doc != null)
	        {
	            Node item = doc.getElementsByTagName("CauHinh").item(0);
	            DOMUltil.printDOM(item);
	            doc = insertItemCH(doc, item, Servername, userName, password, ip, 
	            		UserNameLearner, PassLearner, autologin);
	            //DOMUtil1.writeXmlToFile(fileName,document);
	            //Document doc, Node parent, String userName, String ip, String fullName
	        }
	        
	        DOMUltil.writeXmlToFile(fName,doc);
	        return doc;
		}
		
		/**
		 * Hàm tạo cấu trúc file IPlist, lưu ý cần gọi hàm này trước khi gọi hàm insert ip
		 * @param doc
		 * @param fName
		 * @return
		 */
		public static Document WriteXMLCH(Document doc, String fName)
		{
			return insertRoot(doc, fName, "CauHinh");
		}
				
	////Thông tin gói tin gởi feedback
		 private static Document insertItemFB(Document doc, Node parent, 
				 String title, int idpart, int iddetaillearning, int idex, String sFeedback)
		  {
			// Insert child Item
				Element e = doc.createElement("Feedback");
				parent.appendChild(e);

				e.setAttribute("Title", title);
				e.setAttribute("IDPart", idpart+"");
				e.setAttribute("IDDetailLearning", iddetaillearning+"");
				e.setAttribute("Content", sFeedback);
				e.setAttribute("IDEx", idex + "");
				
				return doc;
		  }
		 //////////////////////////////////////////////////////////////////////////////////////////
		 
		 /**
		  * Delete cấu hình
		  */
			public static Document deleteFB(Document doc, String fName, String Title)
			{
				if(doc != null)
				{
					NodeList resList = doc.getElementsByTagName("Feedback");
					int n = resList.getLength();
					for(int i = 0; i< n; i++)
					{
						Element e = (Element)resList.item(i);
						if(e.getAttribute("Title").equals(Title))
						{
							Node parent = e.getParentNode();
						  	parent.removeChild(e);
						}
						break;
					}					
				}
				DOMUltil.writeXmlToFile(fName,doc);
				return doc;
			}
			/**
			  * Delete cấu hình theo username
			  */
			//Xóa một Learner trong listip
			public static Document deleteFB(Document doc, String fName)
			{
				if(doc != null)
				{
					NodeList resList = doc.getElementsByTagName("Feedback");
					int n = resList.getLength();
					for(int i = 0; i< n; i++)
					{
						Element e = (Element)resList.item(i);
						Node parent = e.getParentNode();
					  	parent.removeChild(e);
						
					}					
				}
				DOMUltil.writeXmlToFile(fName,doc);
				return doc;
			}
			/**
			 * hàm insert một ip vào ip List
			 * @param doc
			 * @param fName
			 * @param ip
			 * @return
			 */
			public static Document insertFB(Document doc, String fName, 
					String title, int idpart, int iddetaillearning, int idex, String sFeedback)
			{
				if(doc != null)
		        {
		            Node item = doc.getElementsByTagName("Exercises").item(0);
		            DOMUltil.printDOM(item);
		            doc = insertItemFB(doc, item, title, idpart, iddetaillearning, idex, sFeedback);
		        }
		        
		        DOMUltil.writeXmlToFile(fName,doc);
		        return doc;
			}
			
			/**
			 * Hàm tạo cấu trúc file IPlist, lưu ý cần gọi hàm này trước khi gọi hàm insert ip
			 * @param doc
			 * @param fName
			 * @return
			 */
			public static Document WriteXMLFB(Document doc, String fName)
			{
				return insertRoot(doc, fName, "Exercises");
			}
			
		////Thông tin gói tin gởi setting
		 private static Document insertItemSetting(Document doc, Node parent, 
				 int timefb, Boolean autofb, int timefeel, Boolean autofeel, Boolean autoshare, int save)
		  {
			// Insert child Item
				Element e = doc.createElement("Info");
				parent.appendChild(e);

				e.setAttribute("TimeFB", timefb+"");
				e.setAttribute("AutoFB", autofb+"");
				e.setAttribute("TimeFeel", timefeel+"");
				e.setAttribute("AutoFeel", autofeel+"");
				e.setAttribute("AutoShare", autoshare + "");
				e.setAttribute("SaveChat", save + "");
				
				return doc;
		  }
		 //////////////////////////////////////////////////////////////////////////////////////////
		 
		 /**
		  * Delete cấu hình
		  */
			public static Document deleteSetting(Document doc, String fName, String TimeFB)
			{
				if(doc != null)
				{
					NodeList resList = doc.getElementsByTagName("Info");
					int n = resList.getLength();
					for(int i = 0; i< n; i++)
					{
						Element e = (Element)resList.item(i);
						if(e.getAttribute("TimeFB").equals(TimeFB))
						{
							Node parent = e.getParentNode();
						  	parent.removeChild(e);
						}
						break;
					}					
				}
				DOMUltil.writeXmlToFile(fName,doc);
				return doc;
			}
			/**
			  * Delete cấu hình theo username
			  */
			//Xóa một Learner trong listip
			public static Document deleteSetting(Document doc, String fName)
			{
				if(doc != null)
				{
					NodeList resList = doc.getElementsByTagName("Info");
					int n = resList.getLength();
					for(int i = 0; i< n; i++)
					{
						Element e = (Element)resList.item(i);
						Node parent = e.getParentNode();
					  	parent.removeChild(e);
						
					}					
				}
				DOMUltil.writeXmlToFile(fName,doc);
				return doc;
			}
			/**
			 * hàm insert một ip vào ip List
			 * @param doc
			 * @param fName
			 * @param ip
			 * @return
			 */
			public static Document insertSetting(Document doc, String fName, 
					int timefb, Boolean autofb, int timefeel, Boolean autofeel, Boolean autoshare, int save)
			{
				if(doc != null)
		        {
		            Node item = doc.getElementsByTagName("Setting").item(0);
		            DOMUltil.printDOM(item);
		            doc = insertItemSetting(doc, item, timefb, autofb, timefeel, autofeel, autoshare, save);
		        }
		        
		        DOMUltil.writeXmlToFile(fName,doc);
		        return doc;
			}
			
			/**
			 * Hàm tạo cấu trúc file IPlist, lưu ý cần gọi hàm này trước khi gọi hàm insert ip
			 * @param doc
			 * @param fName
			 * @return
			 */
			public static Document WriteXMLSetting(Document doc, String fName)
			{
				return insertRoot(doc, fName, "Setting");
			}
			
			/**
			 * Ghi danh sách câu hỏi xuống file
			 * @param path
			 * @param quesList
			 * @return
			 */
			public static Document WriteQuestion(String path, ArrayList<ArrayList<Object>> quesList)
			{
				Document doc = null;
				doc = insertRoot(doc, path, "QuestionList");
				int n = quesList.size();
				for(int i = 0; i < n; i++)
				{
					Node root = doc.getElementsByTagName("QuestionList").item(0);
					Node parent = doc.createElement("Question");
					root.appendChild(parent);
					
					int type = Integer.valueOf(quesList.get(i).get(0).toString());
					
					Node child = doc.createElement("Type");
					parent.appendChild(child);
					
					Node value = doc.createTextNode(quesList.get(i).get(0).toString());
					child.appendChild(value);
					
					child = doc.createElement("Content");
					parent.appendChild(child);
					
					value = doc.createTextNode(quesList.get(i).get(1).toString());
					child.appendChild(value);
					
					Node optList = doc.createElement("OptionList");
					parent.appendChild(optList);
					int length = quesList.get(i).size();
					switch (type) {
					case 5:
					{
						for(int j = 0; j< length - 2; j++)
						{
							child = doc.createElement("Option");
							optList.appendChild(child);

							value = doc.createTextNode(quesList.get(i).get(2+j).toString());
							child.appendChild(value);
						}
						break;
					}
					default:
					{
						for(int j = 0; j< length - 2; j+=2)
						{
							Element e = doc.createElement("Option");
							optList.appendChild(e);
							
							e.setAttribute("isAnswer", quesList.get(i).get(2+j).toString());
							e.setTextContent(quesList.get(i).get(2+j+1).toString());
						}
						break;	
					}
					}
					
				}
				DOMUltil.writeXmlToFile(path, doc);
				return doc;
			}
			
			
			//Xóa một Learner trong listip
			public static Document deleteIDMax(Document doc, String fName)
			{
				if(doc != null)
				{
					NodeList resList = doc.getElementsByTagName("Info");
					int n = resList.getLength();
					for(int i = 0; i< n; i++)
					{
						Element e = (Element)resList.item(i);
						Node parent = e.getParentNode();
					  	parent.removeChild(e);
						
					}					
				}
				DOMUltil.writeXmlToFile(fName,doc);
				return doc;
			}
			/**
			 * hàm insert một ip vào ip List
			 * @param doc
			 * @param fName
			 * @param ip
			 * @return
			 */
			public static Document insertIDMax(Document doc, String fName, int idmax)
			{
				if(doc != null)
		        {
		            Node item = doc.getElementsByTagName("IDMax").item(0);
		            DOMUltil.printDOM(item);
		            doc = insertItemIDMax(doc, item, idmax);
		        }
		        
		        DOMUltil.writeXmlToFile(fName,doc);
		        return doc;
			}
			
			/**
			 * Hàm tạo cấu trúc file IPlist, lưu ý cần gọi hàm này trước khi gọi hàm insert ip
			 * @param doc
			 * @param fName
			 * @return
			 */
			public static Document WriteXMLIDMax(Document doc, String fName)
			{
				return insertRoot(doc, fName, "IDMax");
			}
			
			private static Document insertItemIDMax(Document doc, Node parent, int idMax)
			  {
				// Insert child Item
					Element e = doc.createElement("Info");
					parent.appendChild(e);

					e.setAttribute("ID", idMax+"");
					
					return doc;
			  }
			
			//------------------------------------------------------------------------------
			//Xóa một Learner trong listip
			public static Document deleteGroup(Document doc, String fName, String TeamLeader)
			{
				NodeList resList = doc.getElementsByTagName("Team");
				int n = resList.getLength();
				for(int i = 0; i< n; i++)
				{
					Element e = (Element)resList.item(i);
					if(e.getAttribute("TeamLeader").equals(TeamLeader))
					{
						Node parent = e.getParentNode();
					  	parent.removeChild(e);
					}
				}		
				DOMUltil.writeXmlToFile(fName,doc);
				return doc;
			}
			public static Document insertGroup(Document doc, String fName,  ArrayList<Object> info, String teamleader)
			{
				if(doc != null)
		        {
					
		            Node item = doc.getElementsByTagName("Group").item(0);
		            DOMUltil.printDOM(item);
		            doc = deleteGroup(doc, fName, teamleader);
		            doc = insertItemGroup(doc, item, info, teamleader);
		        }
		        
		        DOMUltil.writeXmlToFile(fName,doc);
		        return doc;
			}
			public static Document WriteXMLGroup(Document doc, String fName)
			{
				return insertRoot(doc, fName, "Group");
			}
			
			private static Document insertItemGroup(Document doc, Node parent, ArrayList<Object> arrInfo, String username)
			  {
				// Insert child Item
					Element e = doc.createElement("Team");
					parent.appendChild(e);

					e.setAttribute("TeamLeader", username);
					e.setAttribute("IDDetailLearning", "");
					e.setAttribute("NameExercises", "");
					e.setAttribute("FileName", "");
					e.setAttribute("Time", "");
					for(int i = 0;i<arrInfo.size();i+=3)
					{
						//tạo node ip
						Element nodeChild = doc.createElement("Info");
						e.appendChild(nodeChild);
	
						nodeChild.setAttribute("UserName", arrInfo.get(i).toString());
						nodeChild.setAttribute("FullName", arrInfo.get(i+1).toString());
						nodeChild.setAttribute("IP",  arrInfo.get(i+2).toString());
					}
					return doc;
			  }
			
			public static Document UpdateFileName(Document doc, String filename, int iddetaillearning, String nameex,
					String teamleader, String filepath, long time)
			{
				try {
					NodeList resList = doc.getElementsByTagName("Team");
					int n = resList.getLength();
					for(int i = 0; i< n; i++)
					{
						Element e = (Element)resList.item(i);
						if(e.getAttribute("TeamLeader").equals(teamleader))
						{
							Node staff = doc.getElementsByTagName("Team").item(i);
					 
							// update staff attribute
							NamedNodeMap attr = staff.getAttributes();
							Node nodeAttr = attr.getNamedItem("FileName");
							nodeAttr.setTextContent(filepath);
							nodeAttr = attr.getNamedItem("IDDetailLearning");
							nodeAttr.setTextContent(iddetaillearning+"");
							nodeAttr = attr.getNamedItem("NameExercises");
							nodeAttr.setTextContent(nameex);
							nodeAttr = attr.getNamedItem("Time");
							nodeAttr.setTextContent(time+"");
					 
							// write the content into xml file
							TransformerFactory transformerFactory = TransformerFactory.newInstance();
							Transformer transformer = transformerFactory.newTransformer();
							DOMSource source = new DOMSource(doc);
							StreamResult result = new StreamResult(new File(filename));
							transformer.transform(source, result);
						}
					}
			 
				   } catch (TransformerException tfe) {
					   tfe.printStackTrace();
				   }
				   return doc;
			}
			
			public static Document UpdateMember(Document doc, String filename, String teamleader, 
					String username, String fullname, String ip)
			{
				try 
				{
					NodeList resList = doc.getElementsByTagName("Team");
					int n = resList.getLength();
					for(int i = 0; i< n; i++)
					{
						Element e = (Element)resList.item(i);
						if(e.getAttribute("TeamLeader").equals("chi"))
						{
								//tạo node ip
							Element nodeChild = doc.createElement("Info");
							e.appendChild(nodeChild);
				
							nodeChild.setAttribute("UserName", username);
							nodeChild.setAttribute("FullName", fullname);
							nodeChild.setAttribute("IP",  ip);
						}
					}
			   } catch (Exception tfe) {
				   tfe.printStackTrace();
			   }
			   return doc;
			}
			
			
			
}

